package com.example.forum.controller;

import com.example.forum.commen.AppResult;
import com.example.forum.commen.ResultCode;
import com.example.forum.config.AppConfig;
import com.example.forum.model.User;
import com.example.forum.services.IUserService;
import com.example.forum.utils.MD5Util;
import com.example.forum.utils.StringUtil;
import com.example.forum.utils.UUIDUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.*;

//返回数据的controller
@RestController
//路由映射
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Resource
    private IUserService userService;

    @RequestMapping("/register")
    public AppResult register(String username, String password, String nickname, String passwordRepeat) {
        if (StringUtil.isEmpty(username) || StringUtil.isEmpty(password)
                || StringUtil.isEmpty(nickname) || StringUtil.isEmpty(passwordRepeat)) {
            //返回错误信息
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }

        //校验密码与重复密码是否相同
        if (!password.equals(passwordRepeat)) {
            //打印日志
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            //返回错误信息包
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }

        //准备数据
        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);
        //处理密码
        //1.生成盐
        String salt = UUIDUtil.UUID_32();
        //2.生成密码的密文
        String encryptPassword = MD5Util.md5Salt(password, salt);
        //设置密码和盐
        user.setSalt(salt);
        user.setPassword(encryptPassword);
        //调用service方法
        userService.createNormalUser(user);
        return AppResult.success();
    }

    /*
     * 用户登录
     * */
    @PostMapping("/login")
    public AppResult login(HttpServletRequest request,
                           @RequestParam("username") String username,
                           @RequestParam("password") String password) {
        //1.调用service中的方法
        User user = userService.login(username, password);
        //2.登陆成功将User对象设置达到Session作用域中
        HttpSession session = request.getSession(true);
        session.setAttribute(AppConfig.USER_SESSION, user);
        //3.返回结果
        return AppResult.success();
    }


    @GetMapping("/info")
    public AppResult<User> getUserInfo(HttpServletRequest request,
                                       @RequestParam(value = "id", required = false) Long id) {
        //定义返回的user对象
        User user = null;
        //1.如果id为空，从session中获取用户信息
        if (id == null) {
            HttpSession session = request.getSession(false);
            //判断session和用户信息是否有效
            if (session == null || session.getAttribute(AppConfig.USER_SESSION) == null) {
                //用户未登录
                return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
            }
            user =(User) session.getAttribute(AppConfig.USER_SESSION);
        }else {
            //2.id不为空，从数据据库里按id查询用户信息
            user = userService.selectById(id);
        }
        if(user == null) {
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
            return AppResult.success(user);
    }
    /*
    * 注销登录
    * */
    @GetMapping("/logout")
    public AppResult logout(HttpServletRequest request) {
        //获取session对象
        HttpSession session = request.getSession(false);
        //判断session是否有效
        if(session != null) {
            //打印日志
            log.info("退出成功");
            //表示用户在登录状态，直接消毁session
            session.invalidate();
        }
        return AppResult.success("退出成功");
    }


    /*修改个人信息*/
    @PostMapping("/modifyInfo")
    public AppResult modifyInfo(HttpServletRequest request,
                                @RequestParam(value = "username",required = false) String username,
                                @RequestParam(value = "nickname",required = false) String nickname,
                                @RequestParam(value = "gender",required = false) Byte gender,
                                @RequestParam(value = "email",required = false) String email,
                                @RequestParam(value = "phoneNum",required = false) String phoneNum,
                                @RequestParam(value = "remark",required = false) String remark) {
        //对参数非空校验
        if(StringUtil.isEmpty(username) && StringUtil.isEmpty(nickname)
          && StringUtil.isEmpty(email) && StringUtil.isEmpty(phoneNum)
          && StringUtil.isEmpty(remark) && gender == null) {
            return AppResult.failed("请输入要修改的内容");
        }
        //从session中获取其user
        HttpSession session = request.getSession(false);
        User user = (User)session.getAttribute(AppConfig.USER_SESSION);
        //封装对象
        User updateUser = new User();
        updateUser.setId(user.getId());//id
        updateUser.setUsername(username);//用户名
        updateUser.setNickname(nickname); //昵称
        updateUser.setGender(gender);//性别
        updateUser.setEmail(email);//邮箱
        updateUser.setPhoneNum(phoneNum);//电话号码
        updateUser.setRemark(remark);//个人简介
        //调用service
        userService.modifyInfo(updateUser);
        //查询最新用户信息
        user = userService.selectById(user.getId());
        //最新信息设置到session中
        session.setAttribute(AppConfig.USER_SESSION,user);
        //返回结果
        return AppResult.success(user);
    }


    @PostMapping("/modifyPwd")
    public AppResult modifyPassword(HttpServletRequest request,
                                    @RequestParam("oldPassword") @NonNull String oldpassword,
                                    @RequestParam("newPassword") @NonNull String newpassword,
                                    @RequestParam("passwordRepeat") @NonNull String passwordRepeat) {
        //1.校验原密码与确认密码是否相同
        if(!newpassword.equals(passwordRepeat)) {
            //返回错误描述
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        //2.获取当前登录用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //调用service
        userService.modifyPassword(user.getId(),newpassword,oldpassword);
        //返回结果
        return AppResult.success();
    }
}
